package com.definity.toolkit.web.taglib;

import javax.servlet.jsp.JspException;

import org.apache.commons.beanutils.MethodUtils;

import com.definity.toolkit.i18n.I18nFactory;

public class RadioEnumTag extends ComponentFormTag {

	private static final long serialVersionUID = 3775279674360205948L;
	
	private String enumerated;

	public RadioEnumTag() {

	}
	
	public void setEnumerated(String enumerated) {
		this.enumerated = enumerated;
	}
	
	@Override
	protected String getComponentName() {
		return "radio-enum";
	}

	@Override
	protected String createLabel(String id, String label, Object value, FormTag formTag) {
		return "";
	}
	
	@Override
	protected String createStartTag(String name, String id, Object value) throws JspException {
		return null;
	}

	@Override
	protected String createEndTag(String name, String id, Object value) throws JspException {
		StringBuilder html = new StringBuilder();
		
		Class<?> enumType;
		
		try {
			enumType = Class.forName(enumerated);
		} catch (Exception e) {
			throw new JspException(e);
		}
		
		html.append("<ul id=\"" + id + "\"");
		html.append(createStyleClass("radio-list", "radio-enum"));
		html.append(">");
		
		for (Object type : getValues(enumType)) {
			String item = enumType.getSimpleName() + "." + type.toString();
			String label = I18nFactory.getApplication().tl(item);
			
			String checked = "";
			if (value != null && value.equals(type))
				checked = "checked";
			
			html.append("<li>");
			html.append("<input type=\"radio\" name=\"" + id + "\" value=\"" + type.toString() + "\" " + checked + " />");
			html.append("<label>" + label + "</label>");
			html.append("</li>");
		}
		
		html.append("</ul>");
		
		return html.toString();
	}

	protected Object[] getValues(Class<?> enumType) {
		try {
			return (Object[]) MethodUtils.invokeStaticMethod(enumType, "values", null);
		} catch (Exception e) {
			return null;
		}
	}
	
}
